package com.ft.turorial.spring.boot.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Options.FlushCachePolicy;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.ft.turorial.spring.boot.domain.User;

/**
 * Mapper接口的sql语句可以通过在方法上增加注解，也可以将sql语句配置在 mapper.xml文件中
 * 
 * Mapper接口的扫描，可以在接口类上增加@Mapper，也可以在启动类上增加@MapperScan
 * @author ft
 *
 */
@Mapper
public interface UserRunAsMapper {
	@Select("select user.* from sys_user_runas ur"
			+ " join user on user.id = ur.to_user_id"
			+ " where from_user_id = #{fromUserId,jdbcType=INTEGER}")
    public List<User> findByFromUserIds(Integer fromUserId);
    @Select("select user.* from sys_user_runas ur"
    		+ " join user on user.id = ur.from_user_id"
			+ " where to_user_id = #{toUserId,jdbcType=INTEGER}")
    public List<User> findByToUserIds(Integer toUserId);
    
    @Select("select count(1) from sys_user_runas where from_user_id=#{fromUserId,jdbcType=INTEGER} and to_user_id=#{toUserId,jdbcType=INTEGER}")
    public Long exists(@Param("fromUserId") Integer fromUserId, @Param("toUserId")  Integer toUserId);

    @Insert("insert into sys_user_runas (from_user_id, to_user_id)"
    	+ "values (#{fromUserId,jdbcType=INTEGER}, #{toUserId,jdbcType=INTEGER})")
    @Options(useGeneratedKeys=true,flushCache=FlushCachePolicy.FALSE,timeout=10000)
	public void grantRunAs(@Param("fromUserId")Integer fromUserId, @Param("toUserId")Integer toUserId);
	
	@Delete("delete from sys_user_runas where from_user_id=#{fromUserId,jdbcType=INTEGER} and to_user_id=#{toUserId,jdbcType=INTEGER}")
	@Options(flushCache=FlushCachePolicy.FALSE,timeout=10000)
	public void revokeRunAs(@Param("fromUserId") Integer fromUserId, @Param("toUserId")  Integer toUserId);

}
